import Vue from 'vue'
import promise from 'es6-promise'
import axios from 'axios'
import qs from 'qs'
import { ToastPlugin } from 'bootstrap-vue'
 
promise.polyfill()  // require('es6-promise').polyfill()

const service = axios.create({
  baseURL: '',
  timeout: 5000,
  responseType: 'json',
  withCredentials: false, //cookie 表示跨域请求时是否需要使用凭证
  headers: {
    // application/json;charset=utf-8
    //'Access-Token': 'usertoken'
  }
})

// service.defaults.baseURL = '' //默认域名
service.interceptors.request.use(
  config => {
    let token = vm.$store.getters.getToken;  
    !config.data && (config.data = {}); //设置默认 data
    token && (config.data.token = token); 
    if(!config.headers['Content-Type']){ //设置默认响应头
      config.headers['Content-Type'] = "application/x-www-form-urlencoded"
      config.data = qs.stringify(config.data)
    }
    //config.method === 'OPTIONS'
    return config
  },
  error => {
    ToastPlugin.$bvToast.toast(error, {
      title: '错误提示',
      toaster: 'b-toaster-top-center',
      variant: 'danger',
      solid: true,
      appendToast: true
    })
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    /* // IE 9
    if (response.data == null && response.config.responseType === 'JSON' && response.request.responseText != null) {
      try {
        response.data = JSON.parse(response.request.responseText);
      } catch (e) {
      }
    }
    return response; */
    let info = qs.parse(response.config.data)
    
    if (response.status === 200) {
      let data = response.data || JSON.parse(response.request.responseText)
      let stateCode = data.StateCode
      let res
      switch (stateCode) {
        case 1:
          res = data
          return data
          break
        case 2001: // 需要登录的接口token失效
          window.localStorage.removeItem('token');
          vm.$store.commit('setToken', null);
          setTimeout(function(){
            info.noNeedLogin || (vm.$router.push({path:'/home/login'}))
          },100)
          break
        case 401:
            res = data
            info.noMessage ||
            ( 
              ToastPlugin.$bvToast.toast(data.message, {
                title: '错误提示',
                toaster: 'b-toaster-top-center',
                variant: 'danger',
                solid: true,
                appendToast: true
              })
            )
            break
        case 0:
          res = data
          info.noMessage || 
          ( 
          ToastPlugin.$bvToast.toast(data.message, {
            title: '错误提示',
            toaster: 'b-toaster-top-center',
            variant: 'danger',
            solid: true,
            appendToast: true
          })
          ) 
          return data
          break
        default:
          res = data
      }
      res = data
      return Promise.reject(res)
      // return res
      // return Promise.resolve(response)
    } else {
      return Promise.reject(response)
    }
  },
  error => {
    if (error.response.status) {
      switch (error.response.status) {
        case 500:
            ToastPlugin.$bvToast.toast('服务器修复中...', {
              title: '错误提示',
              toaster: 'b-toaster-top-center',
              variant: 'danger',
              solid: true,
              appendToast: true
            })
            break;
        case 401:
           vm.$router.push({path:'/home/login'})
            break;
        case 403:
            ToastPlugin.$bvToast.toast('登录过期，请重新登录', {
              title: '错误提示',
              toaster: 'b-toaster-top-center',
              variant: 'danger',
              solid: true,
              appendToast: true
            })
            // 清除token
            localStorage.removeItem('token');

            vm.$store.commit('setToken', null);
            // 跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面
            setTimeout(() => {
              vm.$router.push({path:'/home/login'})
            }, 1000);
            break;
        // 404请求不存在
        case 404:
            ToastPlugin.$bvToast.toast('网络请求不存在', {
              title: '错误提示',
              toaster: 'b-toaster-top-center',
              variant: 'danger',
              solid: true,
              appendToast: true
            })
            break;
        // 其他错误，直接抛出错误提示
        default:
            ToastPlugin.$bvToast.toast( error.response.data.message, {
              title: '错误提示',
              toaster: 'b-toaster-top-center',
              variant: 'danger',
              solid: true,
              appendToast: true
            })
      }
      return Promise.reject(error.response);
    }
  }
)

Vue.prototype.$http = service

export default service

